  

import { defineComponent } from 'vue'
import { useMessage } from 'naive-ui'
import Dag from '../../components/dag'
import { useThemeStore } from '@/store/theme/theme'
import { useRoute, useRouter } from 'vue-router'
import {
  SaveForm,
  TaskDefinition,
  Connect,
  Location
} from '../../components/dag/types'
import { createProcessDefinition } from '@/service/modules/process-definition'
import { useI18n } from 'vue-i18n'
import Styles from './index.module.scss'

interface SaveData {
  saveForm: SaveForm
  taskDefinitions: TaskDefinition[]
  connects: Connect[]
  locations: Location[]
}

export default defineComponent({
  name: 'WorkflowDefinitionCreate',
  setup() {
    console.log('---> WorkflowDefinitionCreate')
    const theme = useThemeStore()

    const message = useMessage()
    const { t } = useI18n()
    const route = useRoute()
    const router = useRouter()
    const projectCode = Number(route.params.projectCode)

    const onSave = ({
      taskDefinitions,
      saveForm,
      connects,
      locations
    }: SaveData) => {
      const globalParams = saveForm.globalParams.map((p) => {
        return {
          prop: p.key,
          value: p.value,
          direct: 'IN',
          type: 'VARCHAR'
        }
      })
      console.log('createProcessDefinition',taskDefinitions)


      taskDefinitions.forEach(item=> {
            for (let v of locations){
               if(item.code === v.code){
                item.x = v.x
                item.y = v.y
               }
            }
      })
      
      let params = {
         name: saveForm.name,
         description : saveForm.description,
         executionType : saveForm.executionType,
         globalParams : globalParams,
         taskNodeParams: taskDefinitions,
         taskRelationList: connects,
         timeout: saveForm.timeoutFlag ? saveForm.timeout : 0,
      }


      console.log('params--->',params)
   
      createProcessDefinition(
        {
          taskDefinitionJson: JSON.stringify(taskDefinitions),
          taskRelationJson: JSON.stringify(connects),
          locations: JSON.stringify(locations),
          name: saveForm.name,
          tenantCode: saveForm.tenantCode,
          executionType: saveForm.executionType,
          description: saveForm.description,
          globalParams: JSON.stringify(globalParams),
          timeout: saveForm.timeoutFlag ? saveForm.timeout : 0
        },
        projectCode
      ).then((ignored: any) => {
        message.success(t('project.dag.success'))
        router.push({ path: `/projects/workflow-definition` })
      })
    }

    return () => (
      <div
        class={[
          Styles.container,
          theme.darkTheme ? Styles['dark'] : Styles['light']
        ]}
      >
        <Dag projectCode={projectCode} onSave={onSave} />
      </div>
    )
  }
})
